<template>
  <div class="cateManager">
    <myheader title="栏目管理">
      <template v-slot:left>
        <van-icon name="arrow-left" @click="$router.go(-1)" />
      </template>
    </myheader>
    <div class="delCate">
      <h3>点击删除频道</h3>
      <div class="list">
        <span v-for="item in cateList" :key="item.id" @click="remove(item)">{{
          item.name
        }}</span>
      </div>
    </div>
    <div class="addCate">
      <h3>点击添加频道</h3>
      <div class="list">
        <span v-for="value in unaddCate" :key="value.id" @click="add(value)">{{
          value.name
        }}</span>
      </div>
    </div>
  </div>
</template>

<script>
import myheader from "../components/myheader.vue";
import { getCateList } from "@/apis/category";
export default {
  data() {
    return {
      cateList: "", //这个存储已经添加的栏目
      unaddCate: "", //未添加的栏目
    };
  },
  components: {
    myheader,
  },
  mounted() {
    // 先获取本地存储数据，如果没有数据，才向后台发请求
    this.cateList = JSON.parse(localStorage.getItem("cateList")) || [];
    this.unaddCate = JSON.parse(localStorage.getItem("unaddCate")) || [];

    if (this.cateList.length == 0 && this.unaddCate.length == 0) {
      getCateList().then((res) => {
        console.log(res);
        this.cateList = res.data.data;
        this.cateList.splice(0, 2);
      });
    }
  },
  methods: {
    remove(item) {
      this.unaddCate.push(item);
      // 添加完同时还要将未添加栏目的item移除
      this.cateList = this.cateList.filter((v) => {
        return v.id !== item.id;
      });

      localStorage.setItem("cateList", JSON.stringify(this.cateList));
      localStorage.setItem("unaddCate", JSON.stringify(this.unaddCate));
    },
    // 将当前两个数组添加到本地存储
    add(value) {
      this.cateList.push(value);
      // 添加完同时还要将未添加栏目的item移除
      this.unaddCate = this.unaddCate.filter((v) => {
        return v.id !== value.id;
      });

      localStorage.setItem("cateList", JSON.stringify(this.cateList));
      localStorage.setItem("unaddCate", JSON.stringify(this.unaddCate));
    },
  },
};
</script>

<style lang="less" scoped>
.delCate,
.addCate {
  padding: 10px;
  h3 {
    line-height: 30px;
    font-weight: bold;
  }
  .list {
    display: flex;
    flex-wrap: wrap;
    span {
      width: 21%;
      border: 1px solid #ccc;
      margin: 5px;
      padding: 10px 15px;
      text-align: center;
    }
  }
}
</style>